$(function(){
	
	var now_question_type = parseInt($('select[name=questions_type]').val());
	var nowquesid = parseInt($('#question_id').val());
	if(typeof(now_question_type) == 'undefined' || isNaN(now_question_type) || isNaN(nowquesid )|| typeof(nowquesid) == 'undefined' || nowquesid == 0 ) {
		initOptions(0);
	} else {
	    updateOptions(now_question_type,nowquesid);
	}
	
	$(document).on('change','.question-type',function(){
		var value = parseInt($(this).val());
		initOptions(value);
	});
	
	$(document).on('click','.add-option',function(){
		var option = getOptions('radio');
        var type = $('.question-type').val();
        if(type == 1){
        	option = getOptions('checkbox');
        	type = 'checkbox';
        }else{
        	type='radio';
        }
        if(isComEmpty(option)){
        	option = 1;
        }
        if(option > 10) {
        	layer.open({
        		 title: '系统提示',
                content: '最多10个选项'
        	});
        	return false;
        }
        var container = $('#question-options-group');
        var optionTemplate = _.template($('#'+type+'-item-template').html());
    	var dataVal = changeIntToEng2(option);
        container.append(optionTemplate({option:option,dataVal:dataVal}));
        
        inintIcheck();
        questionEditorInit();
	});
	$(document).on('click','.option-remove',function(){
		$(this).parent().parent().remove();
	});
	
	$(document).on('click','.question-submit', function () {
		var form = $('#questionsForm');
		var answer='';
		var question_type = form.find('select[name=questions_type]').val()
		var url = $(this).attr('data-uri');

		
		var itembankId = $('#itembank_id').val();
		
		var data = {
			itembank_id:itembankId,
			title:form.find('textarea[name=title]').val(),
            questions_type:question_type,
			options:formDataParse(question_type),	
		};
		var params = {
				url: url,
				type: 'POST',
				dataType: 'json',
				data:data,
		};
		$.ajax(params).done(function(resp){
			if(resp.status == 'success'){
            	BootstrapDialog.alert({title:'提示',message:resp.msg,callback: function(result) {
                    window.location.href= resp.redirectUrl;
	            }});
            }else{
            	BootstrapDialog.alert({title:'提示',message:resp.msg});
            }
		}).fail(function(erro){
			error(erro);
		});
	});
	
});